/*
 * Copyright (c) 2009, ConnectCode Pte Ltd
 *                     http://www.webextractor360.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of ConnectCode nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY ConnectCode Pte Ltd ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL ConnectCode Pte Ltd BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;

using WebExtractor360.look4me.Action;
using WebExtractor360.look4me.Model;
using WebExtractor360.look4me.Framework;
using WebExtractor360.look4me.UserInterface;

namespace WebExtractor360
{
    namespace look4me
    {
        namespace UserInterface
        {

            public partial class MainForm : Form
            {
                public MainForm()
                {

                    Screen screen = Screen.PrimaryScreen;
                    int S_width = screen.Bounds.Width;
                    int S_height = screen.Bounds.Height;

                    InitializeComponent();

                    ExtractorSplashScreen sf = new WebExtractor360.look4me.UserInterface.ExtractorSplashScreen(@".\images\splash.bmp", System.Drawing.Color.FromArgb(128, 128, 128));
                    sf.ShowDialog();

                    this.IsMdiContainer = true;
                    this.treeView1.ExpandAll();
                    ArrayList excludelist = new ArrayList();
                 
                    if (excludelist.Count > 0)
                    {

                        ArrayList removeList = new ArrayList();

                        IEnumerator ie = treeView1.Nodes.GetEnumerator();
                        while (ie.MoveNext())
                        {
                            TreeNode treenode = (TreeNode)ie.Current;
                            if (excludelist.Contains(treenode.Name))
                                removeList.Add(treenode);
                            if (treenode.Nodes.Count > 0)
                            {
                                IEnumerator ien = treenode.Nodes.GetEnumerator();
                                while (ien.MoveNext())
                                {

                                    TreeNode treenoden = (TreeNode)ien.Current;
                                    if (excludelist.Contains(treenoden.Name))
                                        removeList.Add(treenoden);
                 
                                }

                            }
                        }

                        IEnumerator iex = removeList.GetEnumerator();
                        while (iex.MoveNext())
                        {
                            TreeNode removeNode = (TreeNode)iex.Current;
                            removeNode.Remove();
                        }
                    }
                    FormsActivator.ActivateForm(FormsActivator.EXTRACTORFORM, this);

                }

  
                private void aboutToolStripMenuItem_Click_1(object sender, EventArgs e)
                {
                    AboutForm aForm = new AboutForm();
                    aForm.StartPosition = FormStartPosition.CenterParent;
                    aForm.TopMost = true;
  
                    aForm.ShowDialog();
                    Invalidate();
                }

  
                private void exitToolStripMenuItem_Click_1(object sender, EventArgs e)
                {
                    Application.Exit(); 
                }

                public TabControl GetMainTabControl()
                {
                    return tabControl1;
                }

  
                private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
                {
                    
                    foreach (TabForm childForm in this.MdiChildren)
                    {
                        //Check for its corresponding MDI child form
                        if (childForm.BaseTabPage.Equals(tabControl1.SelectedTab))
                        {
                            //Activate the MDI child form
                            childForm.WindowState = FormWindowState.Maximized;
                            childForm.Invalidate(); 
                            childForm.Select();
                            return;

                            
                        }
                    }
                    tabControl1.SelectedIndex = -1;
  
                }


                private void toolStripMenuItem1_DropDownOpened(object sender, EventArgs e)
                {
                    if (tabControl1.SelectedIndex == -1)
                    {
                        saveResultToolStripMenuItem.Enabled = false;
                        saveProcessToolStripMenuItem.Enabled = false;
                        saveProfileToolStripMenuItem.Enabled = false;
                        return;
                    }

                    if (((TabForm)(this.ActiveMdiChild)) == null)
                    {
                        loadSettingsToolStripMenuItem.Enabled = false;
                        saveResultToolStripMenuItem.Enabled = false;
                        saveProcessToolStripMenuItem.Enabled = false;
                        saveProfileToolStripMenuItem.Enabled = false;
                        return;
                    }

                    if (((TabForm)(this.ActiveMdiChild)).SaveResults == 1)
                        saveResultToolStripMenuItem.Enabled = true;
                    else
                        saveResultToolStripMenuItem.Enabled = false;

                    if (((TabForm)(this.ActiveMdiChild)).SaveLinksProcessed == 1)
                        saveProcessToolStripMenuItem.Enabled = true;
                    else
                        saveProcessToolStripMenuItem.Enabled = false;

                    if (((TabForm)(this.ActiveMdiChild)).SaveSettings == 1)
                        saveProfileToolStripMenuItem.Enabled = true;
                    else
                        saveProfileToolStripMenuItem.Enabled = false;
                            
                }

                private void saveResultToolStripMenuItem_Click(object sender, EventArgs e)
                {
                   if (((WorkerForm)(this.ActiveMdiChild)).GetFunctionGroupStatus() == false)
                    {
                       MessageBox.Show("This Operation is currently not allowed as a background job for this Window is running.");
                       return;
                   }

                    try
                    {
                        FileDialog fd = new SaveFileDialog();
                        
                        fd.InitialDirectory = Singleton.AppPath;
                        fd.Filter = "Text Files (*.txt)|*.txt|"+ 
                                    "All Files|";

                        if (fd.ShowDialog() == DialogResult.OK)
                        {



                            string filename = fd.FileName;
                            string[] lines = ((TabForm)(this.ActiveMdiChild)).TextResults.Lines;

                            TextWriter tw = new StreamWriter(filename);
                            // write a line of text to the file
                            int len = lines.Length;
                            for (int x = 0; x < len; x++)
                            {
                                tw.WriteLine(lines[x]);
                            }
                            // close the stream
                            tw.Close();

                            MessageBox.Show("The file has been saved successfully.", "Message");
                        }
                        else
                        {
                            //Do nothing
                        }
                            
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error in saving File.", "Error");

                    }
                }

                private void saveProcessToolStripMenuItem_Click(object sender, EventArgs e)
                {
                    if (((WorkerForm)(this.ActiveMdiChild)).GetFunctionGroupStatus() == false)
                    {
                        MessageBox.Show("This Operation is currently not allowed as a background job for this Window is running.");
                        return;
                    }

                    try
                    {
                        FileDialog fd = new SaveFileDialog();
                        
                        fd.InitialDirectory = Singleton.AppPath;
                        fd.Filter = "Text Files (*.txt)|*.txt|" +
                                    "All Files|";

                        if (fd.ShowDialog() == DialogResult.OK)
                        {



                            string filename = fd.FileName;
                            string[] lines = ((TabForm)(this.ActiveMdiChild)).TextProcess.Lines;

                            TextWriter tw = new StreamWriter(filename);
                            // write a line of text to the file
                            int len = lines.Length;
                            for (int x = 0; x < len; x++)
                            {
                                tw.WriteLine(lines[x]);
                            }
                            // close the stream
                            tw.Close();

                            MessageBox.Show("The file has been saved successfully.", "Message");
                        }
                        else
                        {
                            //Do nothing
                        }

                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error in saving File.", "Error");

                    }
                }

                private void saveProfileToolStripMenuItem_Click(object sender, EventArgs e)
                {
                    if (((WorkerForm)(this.ActiveMdiChild)).GetFunctionGroupStatus() == false)
                    {
                        MessageBox.Show("This Operation is currently not allowed as a background job for this Window is running.");
                        return;
                    }

                    try
                    {
                        FileDialog fd = new SaveFileDialog();
                        fd.InitialDirectory = Singleton.GetInstance().AppProfilesPath;
                        fd.Filter = "Profile Settings (*.pst)|*.pst|" +
                                    "All Files|";

                        if (fd.ShowDialog() == DialogResult.OK)
                        {

                            string filename = fd.FileName;

                            ((TabForm)(this.ActiveMdiChild)).PopulateProfile();
                            ProfileValueObject pfo = ((TabForm)(this.ActiveMdiChild)).ProfileValueObjectHolder;

                            Stream s = File.Open(filename, FileMode.OpenOrCreate);
                            BinaryFormatter b = new BinaryFormatter();
                            b.Serialize(s, pfo);
                            s.Close();

                            MessageBox.Show("The Profile has been saved successfully.", "Message");
                        }
                        else
                        {
                            //Do nothing
                        }

                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error in saving File.", "Error");

                    }
                }

                private void loadSettingsToolStripMenuItem_Click(object sender, EventArgs e)
                {

                    try
                    {
                        FileDialog fd = new OpenFileDialog();
                        fd.InitialDirectory = Singleton.GetInstance().AppProfilesPath;
                        fd.Filter = "Profile Settings (*.pst)|*.pst|" +
                                    "All Files|";

                        if (fd.ShowDialog() == DialogResult.OK)
                        {

                            switch (MessageBox.Show("Please confirm that you will like to load this settings. Existing unsaved settings will be overwritten.", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                            {
                                case DialogResult.Cancel:
                                    return;
                                case DialogResult.OK:
                                    break;
                            }

                            string filename = fd.FileName;
                            ProfileValueObject pfo;
                            Stream s = File.Open(filename, FileMode.Open);
                            BinaryFormatter b = new BinaryFormatter();
                            pfo=(ProfileValueObject)b.Deserialize(s);
                            s.Close();
                            FormsActivator.ActivateForm(pfo.ProfileAction, this);
                            ((TabForm)(this.ActiveMdiChild)).ProfileValueObjectHolder = pfo;
                            ((TabForm)(this.ActiveMdiChild)).PopulateForm();
                        }
                        else
                        {
                            //Do nothing
                        }

                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error in opening File.", "Error");

                    }
                }


                private void helplaunchtoolStripMenuItem_Click(object sender, EventArgs e)
                {
                    Help.ShowHelp(this, "look4me.chm");
                    
                }

                private void MainForm_Shown(object sender, EventArgs e)
                {
                    

                }

                private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
                {
                    SerializeAction seAction = new SerializeAction();
                    seAction.Execute();
                }

                private void searchOptionsToolStripMenuItem_Click(object sender, EventArgs e)
                {
                    SearchOptionsForm sForm = new SearchOptionsForm();
                    sForm.StartPosition = FormStartPosition.CenterParent;
                    sForm.TopMost = true;

                    sForm.ShowDialog();
                    Invalidate();

                }

                private void opentexttoolStripMenuItem_Click(object sender, EventArgs e)
                {

                    try
                    {
                        FileDialog fd = new OpenFileDialog();
                        fd.InitialDirectory = Singleton.AppPath;
                        fd.Filter = "All Files|";

                        if (fd.ShowDialog() == DialogResult.OK)
                        {

                            string filename = fd.FileName;
                            StreamReader s = File.OpenText(filename);
                            string alllines = s.ReadToEnd();
                            s.Close();

                            Form returnForm=FormsActivator.ActivateForm(FormsActivator.TEXTPAD, this);
                            ((TextPadForm)returnForm).SetupText(alllines);
                            
                            
                        }
                        else
                        {
                            //Do nothing
                        }

                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error in opening File.", "Error");

                    }

                }

                private void savetexttoolStripMenuItem_Click(object sender, EventArgs e)
                {
                    try
                    {
                        FileDialog fd = new SaveFileDialog();

                        fd.InitialDirectory = Singleton.AppPath;
                        fd.Filter = "Text Files (*.txt)|*.txt|" +
                                    "All Files|";

                        if (fd.ShowDialog() == DialogResult.OK)
                        {


                            string filename = fd.FileName;
                            string[] lines = ((TextPadForm)(this.ActiveMdiChild)).GetText();


                            TextWriter tw = new StreamWriter(filename);
                            // write a line of text to the file
                            int len = lines.Length;
                            for (int x = 0; x < len; x++)
                            {
                                tw.WriteLine(lines[x]);
                            }
                            // close the stream
                            tw.Close();

                            MessageBox.Show("The file has been saved successfully.", "Message");
                        }
                        else
                        {
                            //Do nothing
                        }

                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error in saving File.", "Error");

                    }
                }

                private void treeView1_DoubleClick(object sender, EventArgs e)
                {
                    if (treeView1.SelectedNode.Name == null)
                        return;
                    if (treeView1.SelectedNode.Name.ToString().Equals("Phone"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?:(phone|tel|telephone)[\S\s]*?)(?<PARAM1>[\+\(\{\[\'\d][\'\(\)\{\}\[\]\.\+\*\-\'\d ]{4,22})");
                    else if (treeView1.SelectedNode.Name.ToString().Equals("Fax"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?:fax[\S\s]*?)(?<PARAM1>[\+\(\{\[\'\d][\'\(\)\{\}\[\]\.\+\*\-\'\d ]{4,22})");
                    else if (treeView1.SelectedNode.Name.ToString().Equals("Emails"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?:mailto\s*:)(?<PARAM1>.*?)(?:[\s>""'])");
                    else if (treeView1.SelectedNode.Name.ToString().Equals("URLs"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?:href\s*=)(?:[\s""']*)(?!#|mailto|location.|javascript)(?<PARAM1>.*?)(?:[\s>""'])");
                    else if (treeView1.SelectedNode.Name.ToString().Equals("Images"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?:src\s*=)(?:[\s""']*)(?<PARAM1>.*?\.(jpg|png|gif|emf|bmp|wmf))(?:[\s>""'])");
                    else if (treeView1.SelectedNode.Name.ToString().Equals("Phrases"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?<PARAM1>(.*keyword.*)?)");
                    else if (treeView1.SelectedNode.Name.ToString().Equals("URLTITLE"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?:href\s*=)(?:[\s""']*)(?!#|mailto|location.|javascript)(?:.*)(?:[>])(?<PARAM1>.*?)(?:</a[\s>""'])");
                    else if (treeView1.SelectedNode.Name.ToString().Equals("Table"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?:<table>)(?<PARAM1>(.*\r\n)*?)(?:</table>)");
                    else if (treeView1.SelectedNode.Name.ToString().Equals("HTMLHEAD"))
                        ((WorkerForm)Singleton.GetInstance().GetForm(FormsActivator.EXTRACTORFORM)).SetExpressions(@"(?:<head>)(?<PARAM1>(.*\r\n)*?)(?:</head>)");
                    
                }

                private void extractToolStripMenuItem_Click(object sender, EventArgs e)
                {
                    FormsActivator.ActivateForm(FormsActivator.EXTRACTORFORM, this);
                }

            }
        }
    }
}